﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace HJ212_Common
{
    public class PlugingManager
    {
        //插件装载器
        public ArrayList Plugins = new ArrayList();
        //插件FullName
        public ArrayList PlugFullName = new ArrayList();
        //插件类型
        public ArrayList PlugTypes = new ArrayList();

        private string pluginPath = "plugins";

        #region 构造函数
        /// <summary>
        /// PlugingManager插件加载
        /// </summary>
        /// <param name="EndsWith">加载指定插件（插件名称以指定名称结尾）</param>
        /// <param name="InterfaceName">插件接口名称</param>
        public PlugingManager(string EndsWith, string InterfaceName)
        {

            //获取插件目录(plugins)下所有文件
            string[] files = Directory.GetFiles(Application.StartupPath + @"\\" + pluginPath);

            foreach (string file in files)
            {
                if (file.ToUpper().EndsWith(EndsWith.ToUpper()))
                {
                    try
                    {
                        //Assembly ab = Assembly.LoadFrom(file);
                        Assembly ab = null;

                        //先将插件拷贝到内存缓冲
                        byte[] addinStream = null;
                        using (FileStream input = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            BinaryReader reader = new BinaryReader(input);
                            addinStream = reader.ReadBytes((int)input.Length);
                        }
                        ab = Assembly.Load(addinStream); //加载内存中的Dll
                        Type[] types = ab.GetTypes();
                        foreach (Type t in types)
                        {
                            if (t.GetInterface(InterfaceName) != null)
                            {
                                Plugins.Add(ab.CreateInstance(t.FullName));
                                PlugFullName.Add(t.FullName);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }
            }
        }
        #endregion
    }
}
